package com.rtwo.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hasee on 2017/5/25.
 */
@Component
@Aspect
public class ControllerAop {


    @Pointcut("execution(* com.rtwo.test.*.*(..))")
    public void executeSay(){

    }

    @Around("executeSay()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint){
        System.out.println("环绕通知的目标方法名："+proceedingJoinPoint.getSignature().getName());
        try {
            Object obj = proceedingJoinPoint.proceed();
            obj = "121212";
            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    @Before("executeSay()")
    public void beforeSay(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        System.out.println(signature.getName());
        System.out.println(signature.getDeclaringTypeName());
        System.out.println(joinPoint.getSourceLocation().getLine());
        Object[] obj = joinPoint.getArgs();
        if(obj.length>0){
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            Enumeration<String> enumeration = httpServletRequest.getParameterNames();
            Map<String,String> map = new HashMap<>(1);
            while(enumeration.hasMoreElements()){
                String element = enumeration.nextElement();
                map.put(element,httpServletRequest.getParameter(element));
            }
            System.out.println(JSONObject.toJSONString(map));
        }else{
            System.out.println("没有参数");
        }
    }
}
